package yiran.stock.command;

import net.milkbowl.vault.economy.Economy;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import yiran.stock.Stock;
import yiran.stock.StockCommand;
import yiran.stock.StockManager;
import yiran.stock.data.DatabaseManager;
import yiran.stock.lang.LangHelper;
import yiran.stock.output.Logger;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class SellCommand implements StockSubCommand {
    @Override
    public boolean execute(CommandSender sender, String[] args, Stock plugin, StockManager stockManager) {
        if (!stockManager.isMarketOpen()) {
            sender.sendMessage(LangHelper.getString("errors.market-closed"));
            return true;
        }

        Economy economy = plugin.getEconomy();

        if (economy == null || plugin.isEconomyEnabled()) {
            sender.sendMessage(LangHelper.getString("errors.economy-not-ready"));
            return true;
        }

        if (!(sender instanceof Player)) {
            sender.sendMessage(LangHelper.getString("errors.only-player-sell"));
            return true;
        }

        if (args.length < 2) {
            sender.sendMessage(LangHelper.getString("commands.sell-usage"));
            return true;
        }

        Player player = (Player) sender;
        String symbol = args[0].toUpperCase();
        int quantity;

        if (!stockManager.loadStockIfNeeded(symbol)) {
            sender.sendMessage(LangHelper.getString("errors.stock-not-found", symbol));
            return true;
        }

        try {
            quantity = Integer.parseInt(args[1]);
            if (quantity <= 0) throw new NumberFormatException();
        } catch (NumberFormatException e) {
            sender.sendMessage(LangHelper.getString("errors.invalid-quantity"));
            return true;
        }

        int currentHolding = DatabaseManager.getHolding(player.getName(), symbol.toLowerCase());
        if (currentHolding < quantity) {
            sender.sendMessage(LangHelper.getString("errors.insufficient-shares", quantity, currentHolding));
            return true;
        }

        double currentPrice = stockManager.getStockPrice(symbol);
        if (args.length > 2 && "confirm".equalsIgnoreCase(args[2])) {
            long purchaseTime = DatabaseManager.getPurchaseTime(player.getName(), symbol);
            long currentTime = System.currentTimeMillis();
            long cooldown = 24 * 60 * 60 * 1000;

            if (currentTime - purchaseTime < cooldown) {
                long remainingHours = (cooldown - (currentTime - purchaseTime)) / (60 * 60 * 1000);
                sender.sendMessage(LangHelper.getString("errors.sell-cooldown", remainingHours));
                return true;
            }

            if (currentPrice <= 0) {
                sender.sendMessage(LangHelper.getString("errors.invalid-price", symbol));
                return true;
            }

            double totalValue = currentPrice * quantity;
            economy.depositPlayer(player, totalValue);

            try {
                DatabaseManager.addHolding(player.getName(), symbol, -quantity, currentPrice);
            } catch (Exception e) {
                economy.withdrawPlayer(player, totalValue);
                sender.sendMessage(LangHelper.getString("errors.transaction-failed", "数据库操作失败"));
                Logger.error("更新持仓失败: " + e.getMessage());
                return true;
            }

            player.sendMessage(LangHelper.getString("stocks.sell-success", quantity, stockManager.getStockName(symbol), totalValue));
            Logger.info(player.getName() + " sold " + quantity + " shares of " + symbol + " for " + totalValue);
        } else {
            // 添加确认提示
            double totalValue = currentPrice * quantity;
            player.sendMessage(LangHelper.getSafeString("stocks.sell-confirm",
                    quantity, stockManager.getStockName(symbol), totalValue));
            player.sendMessage(LangHelper.getSafeString("commands.confirm-instruction-sell", symbol, quantity));
        }
        return true;
    }

    @Override
    public List<String> tabComplete(CommandSender sender, String[] args, StockManager stockManager) {
        if (!(sender instanceof Player)) {
            return Collections.emptyList();
        }

        Player player = (Player) sender;
        Map<String, Integer> holdings = DatabaseManager.getHoldings(player.getName());

        Set<String> playerStocks = holdings.entrySet().stream()
                .filter(entry -> entry.getValue() > 0)
                .map(Map.Entry::getKey)
                .collect(Collectors.toSet());

        if (args.length == 1) {
            String input = args[0].toLowerCase();
            return playerStocks.stream()
                    .filter(symbol -> symbol.startsWith(input))
                    .collect(Collectors.toList());
        }
        return Collections.emptyList();
    }
}
